package com.hiray.demos.ui_architect.litho.image

import android.graphics.Color
import android.net.Uri
import android.util.Log
import com.facebook.common.util.UriUtil
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.drawee.drawable.ScalingUtils
import com.facebook.drawee.generic.RoundingParams
import com.facebook.litho.Component
import com.facebook.litho.ComponentContext
import com.facebook.litho.annotations.LayoutSpec
import com.facebook.litho.annotations.OnCreateLayout
import com.facebook.litho.annotations.Prop
import com.facebook.litho.annotations.PropDefault
import com.facebook.litho.fresco.FrescoImage


@LayoutSpec
object SingleImageComponentSpec {

    @PropDefault val image =""
    @PropDefault val resId =0
    @PropDefault val widthDp =0f
    @PropDefault val heightDp =0f
    @PropDefault val radius =0f
    @PropDefault val autoSize = false

    @OnCreateLayout
    fun onCreateLayout(
            c: ComponentContext,
            @Prop(optional = true) image: String = "",
            @Prop(optional = true) resId: Int = 0,
            @Prop(optional = true) widthDp: Float = 0f,
            @Prop(optional = true) heightDp: Float = 0f,
            @Prop(optional = true) radius: Float = 0f,
            @Prop(optional = true) autoSize: Boolean = false): Component {
        val uri: Uri
        if (image.isEmpty()) {
            uri = Uri.Builder()
                    .scheme(UriUtil.LOCAL_RESOURCE_SCHEME)
                    .path(resId.toString())
                    .build()
            Log.i("ruiz", "${uri.isAbsolute} ${uri.toString()}")
        } else uri = Uri.parse(image)
        val controller = Fresco.newDraweeControllerBuilder()
                .setUri(uri)
                .build()
        val builder = FrescoImage.create(c).controller(controller)
                .actualImageScaleType(ScalingUtils.ScaleType.FIT_XY)
                .backgroundColor(Color.WHITE)
                .roundingParams(RoundingParams.fromCornersRadius(radius))
        if (autoSize)
            builder
                    .controller(controller)
        else builder
                .widthDip(widthDp)
                .heightDip(heightDp)
        return builder.build()
    }
}